﻿using log4net;
using System;


namespace RemoteData.core.queue
{
    public class QueueWorker<T> : Worker
    {
        public delegate void HandleProc(T data);
        public delegate void PostProc();

        private static ILog logger = LogManager.GetLogger(typeof(QueueWorker<T>));

        public SHQueue<T> recvQueue = new SHQueue<T>(); // 接收者队列
        public HandleProc handleProc = null;  // 消息处理函数
        public PostProc postProc = null;

        public override void Start()
        {
            this.stopFlag = false;
            this.startTime = DateTime.Now;

            if (PreStart() == -1)
            {
                logger.WarnFormat("worker启动失败");
                goto end;
            }

            while (!stopFlag)
            {
                T msg = default(T);
                bool rn = recvQueue.TryDequeue(out msg, 3000);
                if (!rn)
                {
                    logger.WarnFormat("no data available");
                    continue;
                }

                if (handleProc != null)
                {
                    handleProc(msg);
                }
            }

        end:
            AfterStart();

            if (postProc != null)
            {
                postProc();
            }
        }

    }
}
